<?php

namespace app\admin\controller;

use think\Request;

class Topic extends Common{

    public function index(){
        if(Request::instance()->isAjax()){
            $data = input();
            $where = [];
            if (!empty($data['name'])){
                $where['title'] = ['like',['%'.$data['name'].'%']];
            }
            return model('topic')->getDataArr($data['page'],$data['limit'],$where);
        }
        return view('index');
    }


    public function add(){
        $this->view->engine->layout("common/iframe");
        $alias = \app\common\model\Topic::$alias;
        return view('create',['alias'=>$alias]);
    }


    public function save(){
        $data = input();
        return model('topic')->saveData($data,isset($data['id'])?$data['id']:'');
    }


    public function edit(){
        $this->view->engine->layout("common/iframe");
        $id = input('id');
        $data = \app\common\model\Topic::where('id',$id)->find();
        $alias = \app\common\model\Topic::$alias;
        return view('edit',['data'=>$data,'alias'=>$alias]);
    }


    /**
     * 删除
     */
    public function delete(){
        try{
            $id = input('id');
            $article = \app\common\model\Article::where(['is_delete'=>2,'topic_id'=>$id])->count();
            if(!empty($article)){
                exception('请先删除该话题下的文章');
            }

            $topic = \app\common\model\Topic::where(['id'=>$id])->update(['is_delete'=>1]);
            if ($topic){
                return ['code'=>'0','msg'=>'删除成功'];
            }else{
                return ['code'=>'1','msg'=>'删除失败'];
            }
        }catch (\Exception $exception) {
            return json(['code' => 1, 'msg' => $exception->getMessage(), 'data' => []]);
        }
    }

}
